package cz.proks.schoolpupilbook.gae.dao;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import cz.proks.schoolpupilbook.gae.converter.Converter;
import cz.proks.schoolpupilbook.gae.converter.UserConverter;
import cz.proks.schoolpupilbook.gae.dao.PersistenceManager.PersistenceExecutor;
import cz.proks.schoolpupilbook.gae.dbo.UserDBO;
import cz.proks.schoolpupilbook.shared.domain.User;

public class UserDAO extends BaseDAO<UserDBO, User>{
	
	@Override
	protected Class<UserDBO> getDBOClass() {		
		return UserDBO.class;
	}
		
	@Override
	protected Converter<UserDBO, User> getConverter() {
		return new UserConverter();
	}
	
	public User login(final String username, final String password) {
		if (username == null || password == null)
			return null;
		
		return PersistenceManager.execute(new PersistenceExecutor<User>() {
			@Override
			public User doExecute(EntityManager em) {
				UserDBO dbo = null;
				try {
					dbo = (UserDBO) em.createQuery("SELECT FROM " + UserDBO.class.getName() + " WHERE username = :username AND password = :password")
												.setParameter("username", username)
												.setParameter("password", password).getSingleResult();			
				} catch(NoResultException nrex) {}
				
				return new UserConverter().getDomain(dbo);
			}
		}, false);		
	}
	
	public boolean usernameExist(final String username) {
		return PersistenceManager.execute(new PersistenceExecutor<Boolean>() {
			@Override
			public Boolean doExecute(EntityManager em) {
				try {
					UserDBO user = (UserDBO) em.createQuery("SELECT FROM " + UserDBO.class.getName() + " WHERE username = :username")
												.setParameter("username", username)
												.getSingleResult();			
					return user != null;
				} catch(NoResultException nrex) {
					return false;
				}				
			}
		}, false);		
	}
}
